package ca.cbc.msb.persistence;

import ca.cbc.medialib.dao.ProcessingStatusDAO;
import ca.cbc.medialib.entity.ProcessingStatus;
import ca.cbc.medialib.entity.enums.ProcessStatus;
import ca.cbc.msb.entity.MSBMessage;
import ca.cbc.msb.util.ProgressReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : Arash Bizhanzadeh <arash.bizhanzadeh@cbc.ca>
 *         Date: 11-09-27
 *         Time: 12:29 PM
 *         CBC.ca All rights reserved.
 */
public class ProcessingStatusPersistence {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
    private ProcessingStatusDAO processingStatusDAO;
  
    public ProcessingStatusDAO getProcessingStatusDAO() {
		return processingStatusDAO;
	}

	public void setProcessingStatusDAO(ProcessingStatusDAO processingStatusDAO) {
		this.processingStatusDAO = processingStatusDAO;
	}
    
	@Transactional(noRollbackFor = {Exception.class})
    public boolean removeProcessingFlag(MSBMessage message) {
    	if(checkProcessingFlag(message)) {
    		logger.info("^-^-^-^Removing process flag for message({})...", message);
	    	processingStatusDAO.deleteById(message.getNotification().getReleaseId());
	    	ProgressReport.instance.statusReport(message, "Process Status Removed");
    	} else {
    		logger.info("^^--^^Process flag is not in DB for message({}), quit removing...", message);
    		return false;
    	}
    	return true;
    }
    
	@Transactional
    public boolean addProcessingFlag(MSBMessage message) {
		if(!checkProcessingFlag(message)) { 
	    	logger.info("^-^-^-^Setting Processing flag for Message({})...", message);
	    	processingStatusDAO.save(new ProcessingStatus(message.getNotification().getReleaseId(), ProcessStatus.NOTIFIED));
	    	ProgressReport.instance.statusReport(message, "Process Status added");
		} else {
			logger.info("^^--^^Can't Set flag for processing Message({})...", message);
			return false;
		}
		return true;
    }
	
	@Transactional
	public void changeProcessingFlag(MSBMessage message, ProcessStatus ps) {
		if(checkProcessingFlag(message)) { 
	    	logger.info("^-^-^-^Changing Processing flag for Message({}) to {}...", message, ps);
	    	processingStatusDAO.merge(new ProcessingStatus(message.getNotification().getReleaseId(), ps));
	    	ProgressReport.instance.statusReport(message, "Process Status added");
		} else {
			logger.error("^^--^^Can't change flag for processing Message({}) to {}, the message dosenot exist...", message, ps);
		}
	}
	
	private boolean checkProcessingFlag(MSBMessage message) {
		if(processingStatusDAO.findById(message.getNotification().getReleaseId()) != null) {
			return true;
		}
		return false;
	}
}
